package com.itmuch.common.cat.filter;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.AbstractMessage;
import com.itmuch.common.cat.CatMsgConstants;
import com.itmuch.common.cat.feign.CatMsgContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by xi on 2018/8/5.
 * 接受客户端传递过来的参数
 * 服务端接受客户端参数
 * 接受上个服务传递过来的参数
 */
public class HttpCatCrossFliter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(HttpCatCrossFliter.class);
    private static final String DEFAULT_APPLICATION_NAME = "default";
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getRequestURI();
        //默认继承使用过滤器上的rootId
        String messgeId  = Cat.getCurrentMessageId();
        logger.info("HttpCatCrossFliter messeageId:"+messgeId);

        Transaction transaction = Cat.newTransaction("provider-service", requestURI);
        try {
            String root =  request.getHeader(Cat.Context.ROOT);
            String parent =  request.getHeader(Cat.Context.PARENT);
            String child =  request.getHeader(Cat.Context.CHILD);
            logger.info("HttpCatCrossFliter root:{},parent:{},child:{}",root,parent,child);
            if(root!=null && root!="") {
                Cat.Context context = new CatMsgContext();
                context.addProperty(Cat.Context.ROOT,root);
                context.addProperty(Cat.Context.PARENT, request.getHeader(Cat.Context.PARENT));
                context.addProperty(Cat.Context.CHILD, request.getHeader(Cat.Context.CHILD));
                Cat.logRemoteCallServer(context);
                this.createProviderCross(request,transaction);
            }
            filterChain.doFilter(req, resp);
        } catch (Exception e) {
            logger.error("------ Get cat msgtree error : ", e);
            Event event = Cat.newEvent("HTTP_REST_CAT_ERROR", requestURI);
            event.setStatus(e);
            completeEvent(event);
            transaction.setStatus(e.getClass().getSimpleName());
            transaction.addChild(event);
        } finally {
            logger.info("完成数据:"+requestURI);
            transaction.complete();
            transaction.setStatus(Transaction.SUCCESS);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    /**
     * 记录服务器端着边的消息
     * @param request
     */
    private void createProviderCross(HttpServletRequest request, Transaction transaction) {
        Event crossAppEvent = Cat.newEvent(CatMsgConstants.PROVIDER_CALL_APP, request.getHeader(CatMsgConstants.APPLICATION_KEY));    //clientName
        Event crossServerEvent = Cat.newEvent(CatMsgConstants.PROVIDER_CALL_SERVER, request.getRemoteAddr());    //clientIp

        crossAppEvent.setStatus(Event.SUCCESS);
        completeEvent(crossAppEvent);

        crossServerEvent.setStatus(Event.SUCCESS);
        completeEvent(crossServerEvent);

        transaction.addChild(crossAppEvent);
        transaction.addChild(crossServerEvent);
    }
    private void completeEvent(Event event){
        AbstractMessage message = (AbstractMessage) event;
        message.setCompleted(true);
    }
}